package handlers

import (
	"github.com/gin-gonic/gin"
	"restaurant-system/config"
	"restaurant-system/internal/models"
)

// 获取AI配置
func GetAIConfig(c *gin.Context) {
	var aiConfig models.AIServiceConfig
	var rules []models.AIQARule

	if err := config.DB.First(&aiConfig).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取AI配置失败"})
		return
	}
	
	if err := config.DB.Order("priority desc").Find(&rules).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取AI规则失败"})
		return
	}

	c.JSON(200, gin.H{
		"config": aiConfig,
		"rules": rules,
	})
}

// 更新AI配置
func UpdateAIConfig(c *gin.Context) {
	var req struct {
		Enabled bool             `json:"enabled"`
		Name    string          `json:"name"`
		Rules   []models.AIQARule `json:"rules"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "无效的请求数据: " + err.Error()})
		return
	}

	// 开始事务
	tx := config.DB.Begin()

	// 更新配置
	if err := tx.Model(&models.AIServiceConfig{}).Updates(map[string]interface{}{
		"enabled": req.Enabled,
		"name":    req.Name,
	}).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "更新配置失败: " + err.Error()})
		return
	}

	// 更新规则
	if err := tx.Delete(&models.AIQARule{}, "1=1").Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "清空规则失败: " + err.Error()})
		return
	}

	for _, rule := range req.Rules {
		if err := tx.Create(&rule).Error; err != nil {
			tx.Rollback()
			c.JSON(500, gin.H{"error": "创建规则失败: " + err.Error()})
			return
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "提交事务失败: " + err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "更新成功"})
} 